<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link data-th-replace="commons::res">
<style type="text/css">
	body{
		padding: 15px
	}
</style>
</head>
<body>
	<form class="layui-form">
		<input type="hidden" name="id" data-th-value="${role?.id}">
		<div class="layui-form-item">
			<div class="layui-form-label">角色名称:</div>
			<div class="layui-input-block">
				<input type="text" class="layui-input" lay-verify="required" data-th-value="${role?.name}" name="name" placeholder="请输入角色名称">
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-form-label">角色编码:</div>
			<div class="layui-input-block">
				<input type="text" class="layui-input" lay-verify="required|code" data-th-value="${role?.code}" name="code" placeholder="请输入角色编码">
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-form-label">关联资源:</div>
			<div class="layui-input-block">
				<div id="resources"></div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-form-label">详情:</div>
			<div class="layui-input-block">
				<textarea name="describe" class="layui-textarea" data-th-text="${role?.describe}" placeholder="请输入角色详情,如:超级管理员拥有至高无上的权限">
				
				</textarea>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-input-block">
				<button type="button" lay-submit class="layui-btn" lay-filter='role'>保存</button>
			</div>
		</div>
	</form>
	<script type="text/javascript">
		layui.use(['form','jquery','layer','authtree'],function(){
			let form=layui.form
				,$=layui.jquery
				,layer=layui.layer
				,authtree=layui.authtree;
			
			//渲染资源树
			$.get("[[@{/resource/find(roleId=${role?.id})}]]&tree",function(rs){
				for(let i in rs.list){
					rs.list[i].name=rs.list[i].name+"("+rs.list[i].type.name+")"
				}
				let trees=authtree.listConvert(rs.list, {
				    primaryKey: 'id'
				        ,startPid: -1
				        ,parentKey: 'pid'
				        ,nameKey: 'name'
				        ,valueKey: 'id'
				        ,checkedKey: rs.checkeds
				    });
				authtree.render('#resources', trees, {
					inputname: 'resourceIds', 
					layfilter: 'lay-check-auth', 
					autowidth: true,
					themePath: '/modules/authtree/tree_themes/'
				});
			},'json');
			
			
			form.verify({
				code:function(value,item){
					if(!/^\w+$/.test(value)){
						return "角色编码不合法,只能使用字母,数字和下划线";
					}
				}
			})
			form.on("submit(role)",function(data){
				data.field.resourceIds=authtree.getChecked("#resources");
				$.ajax({
					url:'[[@{/role/save}]]',
					type:'post',
					dataType:'json',
					data:data.field,
					success:function(rs){
						if(rs.success){
							var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
							parent.reload();
							parent.layer.msg("保存成功",{icon:6});
							parent.layer.close(index);
							
						}else{
							layer.msg("保存失败",{icon:5});
						}
					}
				})
				return false;
			})
		})
	</script>
</body>
</html>